<template>
	<div class="wrapper" :style="'--status-barHeight:'+0+'px'">
		<div class="header">
			<!-- <view class="back_div">
				<image class="back_img" @click="back_city()" :src="$img_path('/course/city_1.png')" mode="widthFix"></image>
			</view> -->
			<!-- <input class="input" @input="onInput" placeholder="请输入城市名" v-model="searchValue" /> -->
			<headerSearch style="flex: auto;" @searchInput="onInput" bg-color="#EEEEEE" p_color="#AAAAAA" placeholder="请输入城市名" :value="searchValue"></headerSearch>
		</div>
		<scroll-view class="calendar-list" scroll-y="true" :scroll-into-view="scrollIntoId" @scroll="scrollChange">
			<view v-if="disdingwei" id="hot">
				<!-- 定位模块 -->
				<view class="dingwei" style="padding-bottom: 21rpx;border-bottom: 1rpx solid #f5f5f5;">
					<!-- <view class="dingwei_Tips" style="color: #FD845C;font-weight: 400;">
						定位
					</view> -->
					<view class="dingwei_city" style="padding: 0 26rpx 0 22rpx;">
						<view class=" position" @click="positionType==2 ? getWarpweft() : ''">
							<image :src="$img_path('/course/img/2.png')" mode="widthFix"></image>
							<!-- <image v-if="positionType==2" :src="$img_path('/course/city_3.png')" mode="widthFix"></image>
							<image v-else :src="$img_path('/course/city_2.png')" mode="widthFix"></image> -->
							{{positionType==0 ? '...' : positionType==1 ? position : '定位失败'}}
							
							<text>当前定位</text>
						</view>
						<view class="dingweis_div" @click="getWarpweft">
							<text>{{po_tips}}</text> 
						</view>
					</view>
				</view>
				
				<!-- 最近模块 -->
				<view class="dingwei" v-if="Visit.length>=0">
					<view class="dingwei_Tips">
						最近访问
					</view>
					<view class="dingwei_city dingwei_city_zuijin">
						<view class="dingwei_city_one toright" v-for="(item,index) in Visit" :key="item.id" v-if="index<8" @click="back_city(item)">
							{{item.name}}
						</view> 
					</view>
				</view>
				
				<!-- 热门模块 -->
				<view class="dingwei hotlist" v-if="Visit.length>=0">
					<view class="dingwei_Tips">
						热门城市
					</view>
					<view class="dingwei_city dingwei_city_zuijin">
						<view class="dingwei_city_one toright" v-for="(item,index) in hotList" :key="item.id" v-if="index<8" @click="back_city(item)">
							{{item.name}}
						</view> 
					</view>
				</view>

			</view>
			
			<!-- new list cityList -->
			<!-- cityList.city JSON --> 
			<!-- cityList API --> 
			<view v-if="searchValue == ''" v-for="(item, index) in cityList" :id="getId(index)" :key="index">
				<!-- <view class="letter-header" ref="letters">{{ item.initial }}</view>
				<view class="city-div" v-for="(city, i) in item.list" :key="i" @click="back_city(city)">
					<text class="city">{{ city.name }}</text>
				</view> -->
				<view class="letter-header" ref="letters">{{ item.first }}</view>
				<view class="city-div" v-for="(city, i) in item.children" :key="city.id" @click="back_city(city)">
					<text class="city">{{ city.name }}</text>
				</view>
			</view>

			<!-- 城市列表 -->
			<!-- <view v-if="searchValue == ''" v-for="(item, index) in list" :id="getId(index)" :key="index">
				<view class="letter-header">{{ getId(index) }}</view>
				<view class="city-div" v-for="(city, i) in item" :key="i" @click="back_city(city)">
					<text class="city">{{ city.cityName }}</text>
				</view>
			</view> -->
			<!-- 搜索结果 -->
			<view class="city-div" v-for="(item, index) in searchList" @click="back_city(item)">
				<text class="city">{{ item.name }}</text>
			</view>
		</scroll-view>

		<!-- 右侧字母 -->
		<view class="letters" v-if="searchValue == ''">
			<view class="letters-item" @click="scrollTo('hot')">最近</view>
			<view class="letters-item" v-for="(item,i) in letter" :key="i" :class="selectLetter==item ? 'selectLetter' : ''" @click="scrollTo(item)">{{ item }}</view>
		</view>

		<!-- 选中之后字母 -->
		<view class="mask" v-if="showMask">
			<view class="mask-r">{{selectLetter}}</view>
		</view>
	</div>
</template>

<script>
	import {cities} from '@/utils/api/public.js'
	import cityList from './city.json'
	import headerSearch from '@/components/header-search/header-search.vue'
	import Citys from '../city.js';
	export default {
		name:'selectCity',
		components: {
			headerSearch
		},
		props: {
			// cityList:{
			// 	type:Array,
			// 	default:[]
			// }
		},

		computed: {
			hotCity() {
				return Citys.hotCity;
			},

			citys() {
				return Citys.cities;
			}
		},

		data() {
			return {
				statusBarHeight: this.statusBarHeight,
				ImgUrl: this.ImgUrl,
				letter: [],
				selectLetter: '',
				searchValue: '',
				scrollIntoId: '',
				cityList:[],
				
				list: [],
				tId: null,
				searchList: [],
				showMask: false,
				disdingwei: true,
				Visit: [], //最近访问
				hotList:cityList.hot,//热门
				position: '定位成功',
				longitude: '', //经度
				latitude: '', //纬度
				location:{},
				seconds: 3,
				po_tips: '重新定位',
				positionType:0,//0定位中，1成功，2失败
			}
		},

		mounted() {
			this.getCities()
		},
		methods: {
			getCities(){
				cities().then(res=>{
					this.cityList = res.data.cities
					
					this.init()
				})
			},
			init(){
				//获取存储的最近访问
				var that = this
				uni.getStorage({
					key: 'Visit_key',
					success: function(res) {
						that.Visit = res.data
					}
				});
				
				//获取定位 经度纬度
				that.getWarpweft()
				//获取city.js 的程序字母
				var mu = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'w', 'x', 'y',
					'z'
				];
				var tmp = [];
				for (var i = 0; i < mu.length; i++) {
					var item = mu[i];
					let list = this.cityList // first
					for (var j = 0; j < list.length; j++) {
						var py = list[j].first;
						if (py == item.toUpperCase()) {
							if (tmp.indexOf(item) == -1) {
								// this.list[i] = [this.citys[j]];
								tmp.push(item);
								this.letter.push(item.toUpperCase());
							} else {
								// this.list[i].push(this.citys[j]);
							}
						}
					}
				}
			},
			scrollChange(event){
				console.log(this.$refs)
				// this.$refs.letters.forEach((e,i)=>{
				// 	// console.log(e.$el.offsetTop)
				// 	if(e.$el.offsetTop>event.detail.scrollTop-10&&e.$el.offsetTop<event.detail.scrollTop+10){
				// 		// console.log(e.$el.innerHTML)
				// 		this.selectLetter = e.$el.innerHTML
				// 		this.scrollIntoId = e.$el.innerHTML
				// 	}
				// 	// let lTOP,Btop
				// 	// if(i==0){
				// 	// 	lTOP = 0
				// 	// }else{
				// 	// 	lTOP = e.$el.offsetTop
				// 	// }
				// 	// Btop = this.$refs.letters[i+1] ? this.$refs.letters[i+1].$el.offsetTop : e.$el.offsetTop+300
					
				// 	// if(event.detail.scrollTop>=lTOP&&event.detail.scrollTop<Btop){
				// 	// 	this.selectLetter = e.$el.innerHTML
				// 	// }
				// })
			},
			
			getId(index) {
				return this.letter[index];
			},

			scrollTo(letter) {
				this.showMask = true
				this.selectLetter = letter == 'hot' ? '最' : letter
				setTimeout(() => {
					this.showMask = false
				}, 300);
				this.scrollIntoId = letter;
			},


			query(source, text) {
				let res = [];
				var self = this;
				// res = source.filter(item => {
				// 	const arr = [];
				// 	let isHave = false;
				// 	Object.keys(item).forEach(prop => {
				// 		const itemStr = item[prop];
				// 		self.isString(itemStr) &&
				// 			itemStr.split(',').forEach(val => {
				// 				arr.push(val);
				// 			});
				// 	});
				// 	arr.some(val => {
				// 		isHave = new RegExp('^' + text).test(val);
				// 		return isHave;
				// 	});
				// 	return isHave;
				// });
				// console.log(JSON.stringify(res));
				let allArr = []
				source.forEach(e=>{
					// let f = e.list.filter(item=>{
					let f = e.children.filter(item=>{
						const arr = [];
						let isHave = false;
						Object.keys(item).forEach(prop => {
							const itemStr = item[prop];
							self.isString(itemStr) &&
							itemStr.split(',').forEach(val => {
								arr.push(val);
							});
						})
						arr.some(val => {
							isHave = new RegExp('^' + text).test(val);
							return isHave;
						});
						return isHave;
					})
					
					
					allArr = [...allArr,...f]
				})
				console.log(allArr)
				return allArr;
			},

			isString(obj) {
				return typeof obj === 'string';
			},

			onInput(e) {
				const value = e.target.value;
				this.searchValue = value
				
				// let list = this.cityList.city
				let list = this.cityList
				if (value !== '' && list && list.length > 0) {
					const queryData = this.query(list, String(value).trim());
					this.searchList = queryData;
					this.disdingwei = false
				} else {
					this.searchList = [];
					this.disdingwei = true
				}
			},

			back_city(item) {
				if (item) {
					this.$emit('back_city', item);
					//unshift 把数据插入到首位，与push相反
					this.Visit.unshift(item)
					this.searchValue = "";
					this.disdingwei = true
					var arr = this.Visit
					//数组去重
					function distinct(arr) {
						let newArr = []
						for (let i = 0; i < arr.length; i++) {
							if (newArr.indexOf(arr[i]) < 0) {
								newArr.push(arr[i])
							}
						}
						return newArr
					}
					this.Visit = distinct(arr)
					console.log(this.Visit, "---最近访问")
					uni.setStorage({
						key: 'Visit_key',
						data: this.Visit
					});
				} else {
					uni.navigateBack()
					this.$emit('back_city', 'no');
				}

			},
			getWarpweft() {
				var that = this
				that.po_tips = '定位中...'
				that.positionType = 0
				// let countdown = setInterval(() => {
				// 	that.seconds--;
					uni.getLocation({
						type: 'wgs84',
						success: function(res) {
							console.log('当前位置的经度：' + res.longitude);
							console.log('当前位置的纬度：' + res.latitude);
							that.positionType = 1
							that.longitude = res.longitude
							that.latitude = res.latitude
							let arr = []
							let latitude = res.latitude
							let longitude = res.longitude
								that.cityList.forEach(e=>{
									e.children.forEach(s=>{
										let item = JSON.parse(JSON.stringify(s))
										let lat = Number(item.lat)
										let lng = Number(item.lng)
										if(latitude>lat-0.2&&latitude<lat+0.2&&longitude>lng-0.2&&longitude<lng+0.2){
											arr.push(s)
										}
									})
								})
								console.log(arr,'===')
							that.location = arr[0] ? arr[0] : ''
							that.position = arr[0] ? arr[0].name : ''
							uni.setStorageSync('select_city',arr[0]?JSON.stringify(arr[0]):'')
						},
						fail() {
							that.positionType = 2
							console.log('err')
						},
						complete: () => {
							that.po_tips = '重新定位'
						}
					});
				// 	if (that.seconds <= 0) {
				// 		that.seconds = 3
				// 		that.po_tips = '重新定位'
				// 		clearInterval(countdown);
				// 	}
				// }, 1000);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wrapper {
		// position: fixed;
		z-index: 9;
		background: #ffffff;
		height: 100%;
		width: 100%;
		// top: 0px;
		// left: 0px;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: border-box;
	}

	.mask {
		position: absolute;
		bottom: 0upx;
		top: 83upx;
		left: 0upx;
		right: 0upx;
		width: 750upx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: rgba(0, 0, 0, 0);
	}

	.mask-r {
		height: 120upx;
		width: 120upx;
		border-radius: 60upx;
		display: flex;
		background: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
		font-size: 40upx;
		color: #FFFFFF
	}

	.content {
		height: 100%;
		width: 100%;
		background-color: #ffffff;
	}

	.header {
		width: 100%;
		height: 72rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		padding: 10rpx 30rpx 0;
		box-sizing: border-box;
	}


	.back_div {
		// width: 65upx;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		padding-right: 16rpx;
	}

	.back_img {
		width: 48upx;
		height: 48upx;
	}

	.input {
		flex: auto;
		font-size: 28upx;
		// width: 620upx;
		height: 72upx;
		border-radius: 40upx;
		background-color: #F5F5F5;
		padding-left: 20upx;
		padding-right: 20upx;
		box-sizing: border-box;
	}

	.title {
		font-size: 30upx;
		color: white;
	}

	.show {
		left: 0;
		width: 100%;
		transition: left 0.3s ease;
	}

	.hide {
		left: 100%;
		width: 100%;
		transition: left 0.3s ease;
	}


	.title {
		font-size: 30upx;
		color: white;
	}

	.calendar-list {
		// position: absolute;
		// top: 83upx;
		// bottom: 0upx;
		width: 100%;
		// #ifndef MP-WEIXIN
		height: calc(100vh - var(--status-barHeight)  - 190rpx);
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: border-box;
		// #endif
		// #ifdef MP-WEIXIN
		height: calc(100vh - 112rpx);
		// #endif
		background-color: #FFFFFF;
		margin-top: 38rpx;
	}

	.letters {
		position: absolute;
		right: 24upx;
		bottom: 0px;
		width: auto;
		top: 480upx;
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 40rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 40rpx);
	}

	.letters-item {
		margin-bottom: 5upx;
		&.selectLetter{
			color: #25BF7E;
		}
	}

	.letter-header {
		height: 45upx;
		font-weight: bold;
		font-size: 30rpx;
		color: #333333;
		line-height: 42rpx;
		padding-left: 30upx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		// background-color: #ebedef;
		margin-top: 20rpx;

	}

	.city-div {
		width: 660upx;
		height: 80upx;
		margin-left: 30upx;
		border-bottom-width: 2rpx;
		border-bottom-color: #EEEEEE;
		border-bottom-style: solid;
		display: flex;
		align-items: center;
		margin-right: 35upx;
	}

	.city {
		font-weight: 500;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
		// padding-left: 30upx;
	}

	.dingwei {
		width: 100%;
		// padding-top: 25upx;
		box-sizing: border-box;
		margin-bottom: 30upx;
	}

	.dingwei_Tips {
		margin-left: 30upx;
		margin-bottom: 20upx;
		font-weight: bold;
		font-size: 36rpx;
		color: #333333;
		line-height: 50rpx;
	}

	.dingwei_city {
		width: 100%;
		height: auto;
		padding-left: 24upx;
		padding-right: 30upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}
	.position{
		display: flex;
		align-items: center;
		justify-content: center;
		// background: linear-gradient( 90deg, #FFA233 0%, #FB4C4C 100%) !important;
		font-weight: bold;
		font-size: 30rpx;
		line-height: 42rpx;
		color: #333333 !important;
		image{
			width: 36rpx;
			height: 40rpx;
			margin-right: 8rpx;
		}
		&>text{
			font-weight: bold;
			font-size: 24rpx;
			color: #999999;
			line-height: 36rpx;
			margin-left: 11rpx;
		}
	}
	.dingwei_city_one {
		width: calc(25% - 11.25rpx);
		height: 74rpx;
		background: #F5F5F5;
		border-radius: 37rpx;
		font-weight: bold;
		font-size: 26rpx;
		color: #333333;
		line-height: 74rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dingweis_div {
		display: flex;
		align-content: flex-end;
		align-items: center;
		font-weight: bold;
		font-size: 30rpx;
		color: #E72A2A;
		line-height: 42rpx;
	}

	.dingweis {
		width: 32upx;
		height: 32upx;
	}

	.dingwei_city_zuijin {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
	}

	.toright {
		margin-right: 10upx;
		margin-bottom: 16rpx;
	}
</style>
